import axios, { AxiosResponse } from "axios";
import { DeliveryModel } from "../models/Delivery";

class DeliveryApis {
    // 根据订单ID查询配送信息
    queryByOrder(orderId: number | string): Promise<DeliveryModel | undefined> {
        const promise: Promise<DeliveryModel | undefined> = new Promise((resolve, reject) => {
            const params = { order: orderId };
            axios.get('/api/delivery/delivery', { params })
                .then((result: AxiosResponse) => {
                    const code: number = result.data.code;
                    if (code === 200) {
                        const delivery: DeliveryModel | undefined = result.data.data;
                        resolve(delivery);
                    } else {
                        resolve(undefined);
                    }
                })
                .catch((error) => reject(error));
        });
        return promise;
    }

    // 创建配送记录（在订单支付成功后调用）
    createDelivery(delivery: DeliveryModel): Promise<boolean> {
        const promise: Promise<boolean> = new Promise((resolve, reject) => {
            axios.post('/api/delivery/delivery', delivery)
                .then((result: AxiosResponse) => {
                    const code: number = result.data.code;
                    if (code === 200) {
                        resolve(true);
                    } else {
                        resolve(false);
                    }
                })
                .catch((error) => reject(error));
        });
        return promise;
    }

    // 更新配送状态（0: 待发货，1: 配送中，2: 已送达等）
    updateState(id: number, state: number): Promise<boolean> {
        const promise: Promise<boolean> = new Promise((resolve, reject) => {
            const body = { id, state };
            axios.put('/api/delivery/delivery', body)
                .then((result: AxiosResponse) => {
                    const code: number = result.data.code;
                    if (code === 200) {
                        resolve(true);
                    } else {
                        resolve(false);
                    }
                })
                .catch((error) => reject(error));
        });
        return promise;
    }
}

export const deliveryApis: DeliveryApis = new DeliveryApis();